<script setup lang="ts">
import {
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NTreeSelect,
  NPagination,
  useDialog,
  type TreeSelectOption
} from 'naive-ui'
import { h, onMounted, reactive, ref, onBeforeUnmount, onDeactivated } from 'vue'
import { sendRequest } from '@/utils/api'
import type { UserTableRowModel } from '@/api/user'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import TableView from '@/components/TableView.vue'
// import type { InstitutionTreeModel } from '@/api/sysInstitution'
import { useRouter } from 'vue-router'
import useFlush from '@/hooks/useFlush'

useFlush('flushUserPermission', () => queryTableData())
const message = useMessage()
const dialog = useDialog()
const router = useRouter()

const bbgDeptList: any = ref([])
const getBbgDeptList = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'overTime',
    api: 'BbgDeptList'
  })
  if (error) return message.error(error.message)
  bbgDeptList.value = res.data
}
// const treeOptions = shallowRef<InstitutionTreeModel[]>([])
// const treeLoading = ref(false)
// const queryTreeOptions = async () => {
//   try {
//     treeLoading.value = true
//     const [error, res] = await sendRequest<HttpResponse<InstitutionTreeModel[]>>({
//       module: 'sysInstitution',
//       api: 'getTree'
//     })

//     if (error) return message.error(error.message)
//     if (res.code !== 0) return message.error(res.msg)
//     treeOptions.value = res.data
//   } catch (error) {
//     console.log(error)
//   } finally {
//     treeLoading.value = false
//   }
// }

const form = reactive({
  name: null,
  deptId: null
})

const tableData = ref<UserTableRowModel[]>([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
const columns: DataTableColumns<UserTableRowModel> = [
  {
    title: '员工编号',
    key: 'userNumber',
    width: 100,
    align: 'center'
  },
  {
    title: '姓名',
    key: 'userName',
    minWidth: 100,
    align: 'center'
  },
  {
    title: '部门',
    key: 'deptName',
    align: 'center'
  },
  {
    title: '手机号',
    key: 'phone',
    minWidth: 100,
    align: 'center'
  },
  {
    title: '操作',
    key: 'cz',
    align: 'center',
    width: 250,
    fixed: 'right',
    render(e) {
      console.log(e)
      return h('div', null, [
        h(
          NButton,
          {
            style: 'margin-right: 6px',
            quaternary: true,
            color: '#6CB187',
            onClick: () => {
              router.push({
                name: 'copyPermission',
                params: {
                  id: e.id
                }
              })
            }
          },
          {
            default: () => '参照赋权'
          }
        ),
        h(
          NButton,
          {
            quaternary: true,
            color: '#6CB187',
            onClick: () => {
              router.push({
                name: 'bindPermission',
                params: {
                  id: e.id
                },
                query: {
                  redirect: router.currentRoute.value.fullPath
                }
              })
            }
          },
          {
            default: () => '编辑权限'
          }
        )
      ])
    }
  }
]

// 获取数据列表
const tableLoading = ref(false)
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<UserTableRowModel>>({
    module: 'user',
    api: 'list',
    override: {
      params: {
        ...form,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false

  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value = res.data.list
}

const keyUpDown = (e: any) => e.key == 'Enter' && queryTableData(true)

onMounted(() => {
  window.addEventListener('keyup', keyUpDown, false)
  getBbgDeptList()
  queryTableData()
})
onBeforeUnmount(() => {
  dialog.destroyAll()
})
onDeactivated(() => {
  window.removeEventListener('keyup', keyUpDown, false)
  dialog.destroyAll()
})
</script>

<template>
  <TableView class="userp">
    <template #form>
      <NSpace align="center" class="userp-search">
        <NInput v-model:value="form.name" clearable placeholder="姓名" style="--n-height: 44rem" />
        <NTreeSelect v-model:value="form.deptId" clearable filterable placeholder="部门"
          :options="(bbgDeptList as unknown as TreeSelectOption[])" key-field="value" label-field="name" />
        <NButton @click="queryTableData(true)" :disabled="tableLoading" :loading="tableLoading" color="#6CB187" ghost
          style="height: 44rem; width: 78rem">
          查询
        </NButton>
      </NSpace>
    </template>
    <template #table="props">
      <n-data-table v-bind="props" :data="tableData" :columns="columns" :loading="tableLoading" bordered />
    </template>
    <template #pagination>
      <NPagination show-size-picker show-quick-jumper :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount" :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize" @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize">
        <template #prefix>共{{ paginationReactive.itemCount }}条</template>
      </NPagination>
    </template>
  </TableView>
</template>

<style scoped lang="scss">
.userp {
  padding: 29rem 20rem 42rem 30rem;
  gap: 24rem 0;
  color: rgba(0, 0, 0, 0.85);

  .userp-search {

    :deep(.n-tree-select .n-base-selection),
    :deep(.n-select .n-base-selection) {
      --n-height: 44rem !important;
    }
  }
}

.password {
  padding: 25rem 56rem 0 36rem;

  &-form {
    padding: 25rem 33rem 10rem 20rem;

    .n-input {
      width: 200rem;
    }
  }
}
</style>
